package Exercises;

public class 二分搜索 {
    // 测试样例
    int [] arr = {1,4,5,7,8,9,10};
    // 传参传一个有序数组和想查询位置的数
    public static int dichotomy(int arr[],int target){
        int start_index = 0;
        int end_index = arr.length-1;
        int mid_index = (start_index+end_index)/2;
        while(start_index <= end_index){
            if (arr[mid_index] == target){return mid_index;}
            if (arr[mid_index] > target){
                end_index = mid_index - 1;
                mid_index = (start_index + end_index)/2;
            }
            if (arr[mid_index] < target){
                start_index = mid_index + 1;
                mid_index = (start_index + end_index)/2;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        二分搜索 e1 = new 二分搜索();
        System.out.println(dichotomy(e1.arr, 11));
    }
}
